package com.handong.handserialprogram.module.routemap;

import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.KeyEvent;

import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.entities.MapPersonEntity;
import com.handong.handserialprogram.model.status.EmergencyMsg;
import com.handong.handserialprogram.model.status.EmergencyResponse;
import com.handong.handserialprogram.model.status.FootRingStatus;
import com.handong.handserialprogram.module.baiduoverlay.MapMode;
import com.handong.handserialprogram.module.base.BasePresenter;
import com.handong.handserialprogram.module.base.BaseView;
import com.handong.handserialprogram.utils.AMapUtil;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.EventBusUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.SPUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by userKey on 2017/12/1.
 */

public class RouteMapPresenter extends BasePresenter<RouteMapActivity> implements GeocodeSearch.OnGeocodeSearchListener {

    protected static final String TAG = RouteMapPresenter.class.getSimpleName();
    protected LatLng mStartLatLng;
    private Map<String, Marker> mMarkerMap;

    private MaterialDialog mLocatingDialog;
    private boolean mIsCatchCriminal = false;
    private MapMode mMapMode;
    GeocodeSearch geocoderSearch ;
    private String EmployeeMarkerId;
    private String SelectedMarkerId;
    private String SelectedTagId;

    public RouteMapPresenter(BaseView view) {
        super(view);
    }

    protected void init() {
        EventBusUtil.register(this);
        mMarkerMap = new HashMap<>();
        mLocatingDialog = new MaterialDialog.Builder(mView)
                .progress(true, 0)
                .content("正在获取当前位置信息...")
                .canceledOnTouchOutside(false)
                .build();
        mLocatingDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (KeyEvent.KEYCODE_BACK == keyCode) {
                    dialog.dismiss();
                    if (mView != null) mView.finish();
                    return true;
                }
                return false;
            }
        });
        mLocatingDialog.show();
        mMapMode = MapMode.NORMAL;
        try {
            geocoderSearch = new GeocodeSearch(mView);
        } catch (AMapException e) {
            e.printStackTrace();
        }
        geocoderSearch.setOnGeocodeSearchListener(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 10)
    public void receiveAMapLocation(AMapLocation location) {
        if (mView == null || !mView.isResume()) {
            return;
        }
        if (null != mLocatingDialog && mLocatingDialog.isShowing()) {
            mLocatingDialog.dismiss();
            mLocatingDialog = null;
        }
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        mStartLatLng = latLng;
        Marker marker = mMarkerMap.get(TAG);
        if (null == marker) {
            marker = AMapUtil.addMarkerOnMap(mView.getAMap(), latLng, R.drawable.map_police_normal);
            EmployeeMarkerId=marker.getId();
            SelectedMarkerId=marker.getId();
            SelectedTagId=TAG;
            mMarkerMap.put(TAG, marker);
            mView.controlMapPointVisible();
            //mView.refreshTip(location);
            //AMapUtil.locateToCenter(mView.getAMap(), latLng);
        } else
            marker.setPosition(latLng);

        mView.refreshTip(location);
        if(marker.getId().equals(SelectedMarkerId))
        {
            mView.refreshLocateDescription("",location.getDescription());
        }
        //mView.refreshTip(location);
    }

    protected boolean dealMarkerClick(Marker marker) {
        SelectedMarkerId=marker.getId();
        if (mMarkerMap == null || mMarkerMap.isEmpty()) {
            return false;
        }
//        if (mMarkerMap.size() == 1 && marker == mMarkerMap.get(TAG)) {
//            JLog.d(TAG, TAG);
//            return true;
//        }
        Set<Map.Entry<String, Marker>> set = mMarkerMap.entrySet();
        Iterator<Map.Entry<String, Marker>> iterator = set.iterator();
        Map.Entry<String, Marker> entry = null;
        while (iterator.hasNext()) {
            entry = iterator.next();
            if (entry.getValue().getId().equals(marker.getId())) {
//                LatLonPoint latLonPoint=new LatLonPoint(marker.getPosition().latitude,marker.getPosition().longitude);
//                RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200,GeocodeSearch.AMAP);
//                geocoderSearch.getFromLocationAsyn(query);
                SelectedTagId=entry.getKey();
                break;
            }
        }
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 60)
    public void receiveCriminalLocate(MapPersonEntity entity) {
        if (mView == null || !mView.isResume()) {
            return;
        }
        LatLng latLng = new LatLng(entity.getLat(), entity.getLng());
        String id = entity.getId();
        Marker marker = mMarkerMap.get(id);
        if (null == marker) {
            marker = AMapUtil.addMarkerOnMap(mView.getAMap(), latLng, R.drawable.map_criminal_escape);
            mMarkerMap.put(id, marker);
            LatLngBounds bounds = new LatLngBounds.Builder()
                    .include(mStartLatLng)
                    .include(latLng)
                    .build();
            // 改变地图状态
            mView.getAMap().animateCamera(CameraUpdateFactory.newLatLngBounds(bounds,0));

        } else
            marker.setPosition(latLng);
        if(marker.getId().equals(SelectedMarkerId))
        {
            LatLonPoint latLonPoint=new LatLonPoint(marker.getPosition().latitude,marker.getPosition().longitude);
            RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200,GeocodeSearch.AMAP);
            geocoderSearch.getFromLocationAsyn(query);
        }
    }

    private void addMarker(Marker marker, LatLng latLng, String id){
        marker = AMapUtil.addMarkerOnMap(mView.getAMap(), latLng, R.drawable.map_criminal_escape);
        mMarkerMap.put(id, marker);
    }

    protected void locateToCenter(AMap aMap) {
        if (mStartLatLng == null) {
            AppUtil.showShortToast(mView, "正在定位中");
            return;
        }
        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mStartLatLng,17.0f));
        SelectedMarkerId=EmployeeMarkerId;
        SelectedTagId=TAG;
    }

    protected void dealModeChange() {
        if (MapMode.NORMAL ==  mMapMode) {
            if (TextUtils.isEmpty(SPUtil.getStringValue(SPUtil.MISSION_ID))){
                AppUtil.showShortToast(mView, "请先开始上传数据");
                return;
            }
            if (SPUtil.getBooleanValue(SPUtil.CATCH_MODE_TIP)) {
                mView.showCatchModeTipDialog();//提示。
                return;
            }
            AMap aMap = mView.getAMap();
            aMap.clear();
            Marker marker = AMapUtil.addMarkerOnMap(aMap, mStartLatLng, R.drawable.map_police_normal);
            mMarkerMap.put(TAG, marker);
        } else {
            AMap aMap = mView.getAMap();
            aMap.clear();
            Marker marker = AMapUtil.addMarkerOnMap(aMap, mStartLatLng, R.drawable.map_police_normal);
            mMarkerMap.put(TAG, marker);
        }
    }

    protected void showMissRoute(AMap baiduMap, String routeID){
    }

    public boolean isCatchCriminal() {
        return mIsCatchCriminal;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 5)
    public void receiveFootRingList(CopyOnWriteArrayList<FootRingNewEntity> vector) {
        if (mView == null || !mView.isResume()) {
            return;
        }
        for (FootRingNewEntity entity:
                vector) {
            if (entity.getStatus()== FootRingStatus.NORMAL) {
                String id = entity.getRingID();
                Marker marker = mMarkerMap.get(id);
                if (marker != null) {
                    mMarkerMap.remove(id);
                    marker.remove();
                }
            }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveEmergencyResult(EmergencyResponse response) {
        if (mView == null || !mView.isResume()) {
            return;
        }
        mView.dealEmergencyResponse(response);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveEmergencyMsg(EmergencyMsg msg) {
        if (mView == null || !mView.isResume()) {
            return;
        }
        if (msg.isStart()) {
            mView.sendEmergencyRequest();
        } else {
            mView.askUserForEmergency();
        }
    }

    @Override
    protected void exit() {
        EventBusUtil.unRegister(this);
        mMarkerMap.clear();
        mMarkerMap = null;
        super.exit();
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        if (null == regeocodeResult ||  regeocodeResult.getRegeocodeAddress().getFormatAddress().equals("")) {
            JLog.d(TAG, "SearchResult.ERRORNO.NO_ERROR");
            return;
        }
        JLog.d(TAG, regeocodeResult.getRegeocodeAddress().getFormatAddress() );
        String address=regeocodeResult.getRegeocodeAddress().getFormatAddress();
        if (!SelectedTagId.equals(TAG))
        {
            mView.refreshLocateDescription(SelectedTagId,address);
            //address= SelectedTagId+address;
        }
        else
        {
            mView.refreshLocateDescription("",address);
        }
        //mView.refreshLocateDescription(SelectedTagId,address);
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }
}
